<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts/core';
import { BarChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { getActivityLocations } from '../../api/activity';

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  PieChart,
  CanvasRenderer
]);

const props = defineProps({
  userId: {
    type: String,
    required: true
  },
  dateRange: {
    type: Object,
    default: () => ({})
  },
  viewType: {
    type: String,
    default: 'count' // count, distance, duration, calorie
  }
});

const loading = ref(true);
const chartRef = ref(null);
const chartInstance = ref(null);
const locationData = ref({});

// 获取数据并初始化图表
const initChart = async () => {
  loading.value = true;
  try {
    const params = {
      startDate: props.dateRange.startDate,
      endDate: props.dateRange.endDate
    };
    
    locationData.value = await getActivityLocations(props.userId, params);
    renderChart();
  } catch (error) {
    console.error('获取数据失败', error);
  } finally {
    loading.value = false;
  }
};

// 渲染图表
const renderChart = () => {
  if (!chartRef.value) return;
  
  // 销毁旧实例
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  
  // 创建新实例
  chartInstance.value = echarts.init(chartRef.value);
  
  // 处理数据
  const locations = Object.keys(locationData.value);
  
  // 获取对应的数据属性和单位
  const dataMapping = {
    count: { field: 'count', label: '运动次数', unit: '次' },
    distance: { field: 'totalDistance', label: '运动距离', unit: 'km' },
    duration: { field: 'totalDuration', label: '运动时长', unit: '分钟' },
    calorie: { field: 'totalCalorie', label: '消耗卡路里', unit: 'kcal' }
  };
  
  const currentField = dataMapping[props.viewType].field;
  const currentLabel = dataMapping[props.viewType].label;
  const currentUnit = dataMapping[props.viewType].unit;
  
  // 准备数据
  const data = locations.map(location => {
    let value = locationData.value[location][currentField];
    
    // 时长转换为分钟
    if (currentField === 'totalDuration') {
      value = Math.round(value / 60);
    }
    
    return {
      name: location,
      value: value
    };
  }).sort((a, b) => b.value - a.value);
  
  // 颜色列表
  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
  
  // 图表配置
  const option = {
    title: {
      text: `${currentLabel}分布`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        return `${params[0].name}<br/>${currentLabel}: ${params[0].value} ${currentUnit}`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: currentUnit,
      nameLocation: 'end'
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        width: 80,
        overflow: 'truncate'
      }
    },
    series: [
      {
        name: currentLabel,
        type: 'bar',
        data: data.map(item => item.value),
        itemStyle: {
          color: function(params) {
            return colors[params.dataIndex % colors.length];
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c} ' + currentUnit
        }
      }
    ]
  };
  
  // 设置图表配置
  chartInstance.value.setOption(option);
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chartInstance.value && chartInstance.value.resize();
  });
};

// 监听属性变化时重新渲染图表
watch(() => props.viewType, () => {
  renderChart();
});

watch(() => props.dateRange, () => {
  initChart();
}, { deep: true });

watch(() => props.userId, () => {
  initChart();
});

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
});
</script>

<template>
  <div class="chart-container">
    <div v-if="loading" class="loading">加载中...</div>
    <div ref="chartRef" class="chart" v-else></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
  position: relative;
}
.chart {
  width: 100%;
  height: 100%;
}
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  min-height: 300px;
  color: #999;
  font-size: 14px;
}
</style> 